package com.viphuli.app.tool.handler;

import android.app.Activity;
import android.content.Intent;

import com.offroader.utils.LogUtils;
import com.offroader.utils.StringUtils;
import com.umeng.message.ALIAS_TYPE;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.viphuli.app.tool.bean.page.AccountLoginPage;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.Constants.UserType;
import com.viphuli.app.tool.fragment.AccountAddUserTypeFragment;
import com.viphuli.app.tool.fragment.AccountLoginFragment;

/**
 * 登录
 * 
 * @author li.li
 *
 */
public class AccountLoginResponseHandler extends MyBaseHttpResponseHandler<AccountLoginFragment, AccountLoginPage> {

	@Override
	public void deal() {

		//存储用户信息
		String accessToken = page.getUser().getUid();
		String openId = page.getUser().getUid();
		String expiresTime = String.valueOf(Long.MAX_VALUE);

		AccessTokenKeeper tokenKeeper = new AccessTokenKeeper(accessToken, expiresTime, openId, page.getUser());
		AccessTokenKeeper.keepAccessToken(caller.getActivity(), tokenKeeper);

		//当用户信息里没有用户类型时，跳转到类型添加用户类型信息界面
		int userType = page.getUser().getUserType();
		if (UserType.normal.getValue() != userType && UserType.arrange_admin.getValue() != userType)
			AccountAddUserTypeFragment.go(caller.getActivity());
		else if (StringUtils.isBlank(page.getUser().getUserName())) {
			AccountAddUserTypeFragment.go(caller.getActivity());
		}

		//友盟推送别名
		String deviceToken = UmengRegistrar.getRegistrationId(caller.getActivity());
		if (StringUtils.isNotBlank(deviceToken)) {

			PushAgent mPushAgent = PushAgent.getInstance(caller.getActivity());

			try {
				mPushAgent.addAlias(openId, ALIAS_TYPE.WEIXIN);
			} catch (Throwable e) {
				LogUtils.error(e.getMessage(), e);
			}

		}

		setResultAndFinish();

	}

	/**
	 * 设置结果并结束
	 * @param localName
	 * @param address
	 */
	private void setResultAndFinish() {
		Intent intent = new Intent();
		caller.getActivity().setResult(Activity.RESULT_OK, intent);
		caller.getActivity().finish();
	}

}
